﻿using System.Windows;
using System.Windows.Controls;

namespace DynamicGeometry
{
    public class StringPropertyEditorFactory : BasePropertyEditorFactory<StringPropertyEditor>
    {
        public override bool SupportsProperty(System.Reflection.PropertyInfo property)
        {
            return property.PropertyType == typeof(string)
                && base.SupportsProperty(property);
        }
    }

    public class StringPropertyEditor : LabeledPropertyEditor, IPropertyEditor
    {
        public TextBox TextBox { get; set; }

        protected override UIElement CreateEditor()
        {
            TextBox = new TextBox();
            TextBox.TextChanged += StringPropertyEditor_TextChanged;
            TextBox.AcceptsReturn = true;
            return TextBox;
        }

        protected override void Focus()
        {
            TextBox.Focus();
            if (!string.IsNullOrEmpty(TextBox.Text))
            {
                TextBox.SelectAll();
            }
        }

        bool guard = false;
        void StringPropertyEditor_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (guard)
            {
                return;
            }
            SetValue(TextBox.Text);
        }

        public void Init()
        {
            guard = true;
            var value = Property.GetValue(Target, null);
            TextBox.Text = (value ?? "").ToString();
            guard = false;
        }
    }
}
